package com.zone.core.binding

import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.TextView
import androidx.databinding.BindingAdapter
import java.text.SimpleDateFormat
import java.util.*

/**
 *Author: last
 *Time: 2024-09-04
 *Description: xxx
 */

@BindingAdapter("android:visibility")
fun setVisibility(view: View, isVisibility: Boolean) {
    view.visibility = if (isVisibility) View.VISIBLE else View.GONE
}

@BindingAdapter("android:invisible")
fun setInvisible(view: View, isInvisible: Boolean) {
    view.visibility = if (isInvisible) View.VISIBLE else View.INVISIBLE
}

@BindingAdapter("time", "timeFormat")
fun setTime(textView: TextView, time: Long, format: String) {
    try {
        textView.text = SimpleDateFormat(format, Locale.getDefault()).format(Date(time))
    } catch (e: Exception) {
    }
}

@BindingAdapter("android:text", "spanText", "spanColor")
fun setSearchText(textView: TextView, text: String, span: String, spanColor: Int) {
    //不包含搜索文字则直接设置原文字
    if (!text.contains(span)) {
        textView.text = text
        return
    }

    //搜索文字在原文字的起始位置
    val start = text.indexOf(span)
    //搜索文字结束位置
    val end = start + span.length

    //使用SpannableStringBuilder实现部分文字不同颜色
    val ssbuilder = SpannableStringBuilder(text)
    //ForegroundColorSpan--文字前景色，BackgroundColorSpan--文字背景色
    val colorSpan = ForegroundColorSpan(spanColor)
    ssbuilder.setSpan(colorSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    textView.text = ssbuilder
}

@BindingAdapter("font")
fun setFont(textView: TextView, font: String) {
    val tf = Typeface.createFromAsset(textView.context.assets, font)
    textView.typeface = tf
}
